import Vue from "vue";
import Vuex from "vuex";
import { getCartApi } from "@/service/http.api.js";
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    goodslist: [],
    address: [],
    cartlist: [],
    searchList: [
      "西瓜",
      "蔬菜",
      "西瓜瓜",
      "蔬菜",
      "西瓜",
      "蔬菜",
      "西瓜",
      "蔬菜",
      "西瓜",
      "蔬菜",
      "西瓜123123",
      "蔬菜",
      "西瓜",
      "蔬菜",
      "西瓜",
      "蔬菜",
    ],
    //地址列表
    addresslist: [
      {
        name: "周杰伦",
        addressDetail: "杭州",
        tel: 5555555,
        areaCode: "330102",
      },
    ],
  },

  mutations: {
    //更新地址列表
    changeadd(state, val) {
      state.addresslist.push(val);
    },
    // 设置初始商品列表
    setGoodslist(state, val) {
      state.goodslist = val;
    },
    // 设置商品数量
    setNumber(state, val) {
      console.log(val);
      if (val.number != 0) {
        state.cartlist.forEach((el) => {
          if (el.id == val.id) {
            el.number = val.number;
          }
        });
      } else {
        state.cartlist = state.cartlist.filter((el) => {
          if (el.id == val.id) {
            state.goodslist.forEach((item) => {
              if (item.id == el.id) {
                item.number = 1;
              }
            });
          }
          return el.id != val.id;
        });
      }
    },
    // 单选
    oneChecked(state, val) {
      state.cartlist.forEach((el) => {
        if (el.id == val.id) {
          el.done = val.done;
        }
      });
    },
    // 全选
    allChecked(state, val) {
      state.cartlist.forEach((el) => {
        el.done = val;
      });
    },
    // 加入购物车
    inCart(state, val) {
      console.log(val);
      let flag = state.cartlist.some((el) => el.id == val);
      if (flag) {
        state.cartlist.forEach((el) => {
          if (el.id == val) {
            el.number++;
          }
        });
      } else {
        state.cartlist.push(state.goodslist.filter((el) => el.id == val)[0]);
      }
    },
    inSearch(state, val) {
      state.searchList.unshift(val);
    },
    deleteSearch(state, val) {
      state.searchList = [];
    },
  },
  actions: {
    async getGoodslist({ commit }, val) {
      const { data } = await getCartApi();
      commit("setGoodslist", data);
    },
  },

  plugins: [
    createPersistedState({
      reducer(val) {
        return {
          goodslist: val.goodslist,
          address: val.address,
          cartlist: val.cartlist,
        };
      },
    }),
  ],
});
